/**
 * Copyright (C) 2012  TopicBankEx
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.oc.mba.res;

import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lurencun.android.support.v2.widget.ViewPager;
import com.lurencun.android.support.v2.widget.ViewPagerAdapter;
import com.oc.mba.AppSetting;
import com.oc.mba.R;
import com.oc.mba.entity.AnswerEntity;
import com.oc.mba.entity.TopicEntity;

/**
 * 
 * @author cfuture.chenyoca [桥下一粒砂] (chenyoca@163.com)
 * @date 2012-3-7
 */
public class RandomPracticeAdapter extends ViewPagerAdapter<TopicEntity> {

	private Vibrator mVirator;
	private final Context mContext;
	private Handler mHandler;
	
	public RandomPracticeAdapter(Context context) {
		super(context);
		mContext = context;
		mVirator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
	}

	

	/* (non-Javadoc)
	 * @see com.lurencun.android.support.v2.widget.ViewPagerAdapter#createView(java.lang.Object, int)
	 */
	@Override
	public View createView(TopicEntity entity, int position) {
		final TopicEntity topicEntity = entity;
		ScrollView  topicCell = (ScrollView) mInflater.inflate(R.layout.topic_cell, null);
		TextView index = (TextView)topicCell.findViewById(R.id.topic_index);
		TextView content = (TextView)topicCell.findViewById(R.id.topic_content);
		LinearLayout answerLayout = (LinearLayout)topicCell.findViewById(R.id.topic_answer_layout);
		TextView solutionTitle = (TextView)topicCell.findViewById(R.id.topic_answer_solution_title);
		TextView solutionContent = (TextView)topicCell.findViewById(R.id.solution_content);
		// 题号
		index.setText(String.format(AppSetting.TOPIC_INDEX, position + 1, getCount()));
		// 题干
		content.setText(topicEntity.getTitle());
		// 创建答案组
		try {
			createAnswerGroup(answerLayout, topicEntity, solutionTitle, solutionContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return topicCell;
	}
	
	/**
	 * 创建答案组
	 * @param answerLayout
	 * @param topicEntity
	 * @param solutionContent 
	 * @param solutionTitle 
	 */
	private void createAnswerGroup(LinearLayout answerLayout,final TopicEntity topicEntity, final TextView solutionTitle, final TextView solutionContent){
		final List<AnswerEntity> answerList = topicEntity.getAnswers();
		final int answerSize = answerList.size();
		// 临时保存选项图片
		final ImageView[] tempIconArray = new ImageView[answerSize];
		final RelativeLayout[] tempIconLayout = new RelativeLayout[answerSize];
		
		// 已经完成
		if (topicEntity.isFinish()) {
			// 绘制每个选项
			for (int i=0; i< answerList.size(); i++) {
				final AnswerEntity answer = answerList.get(i);
				RelativeLayout cellLayout = (RelativeLayout) mInflater.inflate(R.layout.answer_selection_cell, null);
				tempIconLayout[i] = (RelativeLayout) cellLayout.findViewById(R.id.answer_icon_layout);
				// 选项图片ABCDE
				final ImageView icon = (ImageView)cellLayout.findViewById(R.id.answer_icon);
				tempIconArray[i] = icon;
				int iconResId = answer.isChecked() ? AppSetting.AnswerIcons.SingleChoice.PRESSED[i] : AppSetting.AnswerIcons.SingleChoice.NORMAL_ARRAY[i];
				icon.setImageResource(iconResId);
				
				if (answer.isChecked()) {
				}
				// 选项内容
				TextView content = (TextView)cellLayout.findViewById(R.id.answer_content);
				content.setText(answer.getContent());
				
				if (answer.isCorrect()) {
					tempIconLayout[i].setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.answer_correct_background));
					icon.setImageResource(AppSetting.AnswerIcons.SingleChoice.PRESSED[i]);
				}else {
					tempIconLayout[i].setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.answer_failure_background));
				}
				if (topicEntity.getSolution()!=null && !topicEntity.getSolution().equals("")) {
					String temp = topicEntity.getSolution();
					solutionTitle.setVisibility(View.VISIBLE);
					solutionContent.setVisibility(View.VISIBLE);
					solutionContent.setText(temp);
				}
				answerLayout.addView(cellLayout);
			}
		}
		// 还没完成
		else {
			// 绘制每个选项
			for (int i=0; i< answerList.size(); i++) {
				final AnswerEntity answer = answerList.get(i);
				RelativeLayout cellLayout = (RelativeLayout) mInflater.inflate(R.layout.answer_selection_cell, null);
				tempIconLayout[i] = (RelativeLayout) cellLayout.findViewById(R.id.answer_icon_layout);
				// 选项图片ABCDE
				final ImageView icon = (ImageView)cellLayout.findViewById(R.id.answer_icon);
				tempIconArray[i] = icon;
				int iconResId = answer.isChecked() ? AppSetting.AnswerIcons.SingleChoice.PRESSED[i] :
					AppSetting.AnswerIcons.SingleChoice.NORMAL_ARRAY[i];
				icon.setImageResource(iconResId);
				
				// 选项内容
				TextView content = (TextView)cellLayout.findViewById(R.id.answer_content);
				content.setText(answer.getContent());
				
				answerLayout.addView(cellLayout);
				
				final int index = i;
				cellLayout.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (topicEntity.isFinish()) {
							return;
						}
						mVirator.vibrate(AppSetting.VIRATOR_PARAMS, -1);
						// 临时记录选中状态
						boolean tempState = !answer.isChecked();
						// 取消选中其他选项
						for(int j=0;j<answerSize;j++){
							AnswerEntity tempAnswer = answerList.get(j);
							tempAnswer.setChecked(false);
							tempIconArray[j].setImageResource(AppSetting.AnswerIcons.SingleChoice.NORMAL_ARRAY[j]);
							if (tempAnswer.isCorrect()) {
								tempIconLayout[j].setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.answer_correct_background));
								tempIconArray[j].setImageResource(AppSetting.AnswerIcons.SingleChoice.PRESSED[j]);
							}
							else {
								tempIconLayout[j].setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.answer_failure_background));
							} 
						}
						// 修改选中状态
						answer.setChecked(tempState);
						
						// 修改选中图标
						int iconResId = answer.isChecked() ? AppSetting.AnswerIcons.SingleChoice.PRESSED[index] : AppSetting.AnswerIcons.SingleChoice.NORMAL_ARRAY[index];
						icon.setImageResource(iconResId);
						if (topicEntity.getSolution()!=null && !topicEntity.getSolution().equals("")) {
							String content = topicEntity.getSolution();
							solutionTitle.setVisibility(View.VISIBLE);
							solutionContent.setVisibility(View.VISIBLE);
							solutionContent.setText(content);
						}
						// 选中了正确答案
						if (tempState && answer.isCorrect()) {
							topicEntity.setCorrect(true);
						}
						topicEntity.setFinish(true);
						// 发送完成消息
						Message msg = Message.obtain(mHandler, 0);
						mHandler.sendMessage(msg);
					}
				});
			}
		}
		
	}

	/* (non-Javadoc)
	 * @see com.lurencun.android.support.v2.widget.ViewPagerAdapter#finishedUpdate(com.lurencun.android.support.v2.widget.ViewPager)
	 */
	@Override
	protected void finishedUpdate(ViewPager container) {
		
	}
	
	/* (non-Javadoc)
	 * @see com.lurencun.android.support.v2.widget.ViewPagerAdapter#startingUpdate(com.lurencun.android.support.v2.widget.ViewPager)
	 */
	@Override
	protected void startingUpdate(ViewPager container) {
		// TODO Auto-generated method stub
		
	}



	public void setHandler(Handler handler) {
		this.mHandler = handler;
	}

}
